<?php
/**
 * websocket
 *
 * Created by PhpStorm.
 * User: dell
 * Date: 2020/2/21
 * Time: 15:27
 */


namespace App\Handlers;


use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Illuminate\Support\Facades\Log;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

class WebSocketHandler implements WebSocketHandlerInterface
{
    public function __construct()
    {

    }

    /**
     * 连接建立时触发
     *
     * @param Server $server
     * @param Request $request
     */
    public function onOpen(Server $server, Request $request)
    {
        Log::info('webSocket连接建立:' . $request->fd);
    }

    /**
     * 收到消息时触发
     *
     * @param Server $server
     * @param Frame $frame
     */
    public function onMessage(Server $server, Frame $frame)
    {
        // $frame->fd 是客户端 id，$frame->data 是客户端发送的数据
        Log::info("从 {$frame->fd} 接收到的数据: {$frame->data}");
        Log::info('链接数:',['sum' => count($server->connections)]);
        foreach($server->connections as $fd){
            if (!$server->isEstablished($fd)) {
                // 如果连接不可用则忽略
                continue;
            }
            // 服务端通过 push 方法向所有连接的客户端发送数据
            $server->push($fd , $frame->data);
        }
    }

    /**
     * 连接关闭时触发
     *
     * @param Server $server
     * @param $fd
     * @param $reactorId
     */
    public function onClose(Server $server, $fd, $reactorId)
    {
        Log::info("webSocket 连接关闭:" . $fd);
    }
}